<template>
    <div class="todo-wrap">
        <el-input v-model="todoVal" placeholder="请输入 todo 内容,回车添加" class="todo-input" @keyup.enter="addTodo"></el-input>

        <div class="todo-top">
            <el-radio-group v-model="todoFilter" @change="filterTodo">
                <el-radio :label="1">所有</el-radio>
                <el-radio :label="2">待完成</el-radio>
                <el-radio :label="3">已完成</el-radio>
            </el-radio-group>
            <div style="width: 40%;display: flex;justify-content: space-between;">
                <el-button type="primary" size="small" @click="showCode">数据</el-button>
                <el-upload class="upload-demo" :limit="1" :show-file-list="false" accept=".json" @change="uploadFile" :auto-upload="false" action="#">
                    <el-button size="small" type="primary">导入</el-button>
                </el-upload>
                <el-button type="primary" size="small" @click="logoutFile">导出</el-button>
            </div>
        </div>

        <el-dialog title="数据源编辑" v-model="codeVisible" width="40%">
            <el-input v-if="todoListString" type="textarea" :autosize="{ minRows: 6, maxRows: 8 }" placeholder="请输入内容" v-model="todoListString" id="myCode"></el-input>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="codeVisible = false">取 消</el-button>
                    <el-button type="primary" @click="updateCode">确 定</el-button>
                </span>
            </template>
        </el-dialog>

        <el-collapse class="todo-list">
            <el-collapse-item v-for="item in filterList" :title="item.value" :class="{ 'todo-finished': item.done }">
                <div class="todo-detail">
                    <div class="todo-detail-item">
                        <span>名称：</span>
                        <el-input style="width: 70%;" placeholder="输入名称" v-model="item.value" @input="updateTodo"></el-input>
                    </div>
                    <div class="todo-detail-item">
                        <span>创建时间：</span>
                        {{ item.date }}
                    </div>
                    <div class="todo-detail-item">
                        <span>已完成：</span>
                        <el-switch v-model="item.done" active-color="#409EFF" inactive-color="#b3b3b3" @change="updateTodo(item)"></el-switch>
                    </div>
                    <div class="todo-detail-item">
                        <span>备注信息：</span>
                        <el-input
                            style="width: 70%;"
                            type="textarea"
                            :autosize="{ minRows: 2, maxRows: 4 }"
                            placeholder="输入备注信息"
                            v-model="item.remark"
                            @input="updateTodo"
                        ></el-input>
                    </div>
                    <div class="todo-detail-item-btn">
                        <el-button type="danger" icon="el-icon-delete" circle @click="deleteTodo(item)"></el-button>
                    </div>
                </div>
            </el-collapse-item>
            <div v-if="filterList.length === 0">暂无事项</div>
        </el-collapse>
    </div>
</template>

<script setup>
import { saveAs } from 'file-saver';
import { storage } from '../util/storage.js';
import { reactive, ref, toRefs, watch, onMounted, getCurrentInstance } from 'vue';
const { ctx } = getCurrentInstance();

onMounted(() => {
    filterTodo();
});

const todoVal = ref();
let todoList = storage.local.get('todoList') || [
    { value: '欢迎使用 TodoList', date: '2021-02-26 16:00:57', remark: '这里可以输入一些备注信息，实时保存\n', done: false },
    { value: '极简设计，私人专属', date: '2021-02-26 16:00:44', remark: '', done: false },
    { value: '数据完全本地存储，安全放心', date: '2021-02-26 15:59:32', remark: '', done: false },
    { value: '可导出导入数据，方便迁移', date: '2021-02-26 15:58:42', remark: '', done: false },
    { value: '可在线编辑数据源，灵活易用', date: '2021-02-26 15:58:25', remark: '', done: false }
];
const addTodo = () => {
    if (!todoVal.value) {
        return;
    }
    const todoItem = {
        value: todoVal.value,
        date: dateFormat(new Date()),
        remark: '',
        done: false
    };
    todoList.unshift(todoItem);
    todoVal.value = '';
    updateTodo();
};

const updateTodo = item => {
    storage.local.set('todoList', todoList);
    filterTodo();
};

const todoFilter = ref(1);
let filterList = ref([]);
const filterTodo = () => {
    filterList.value = todoList.filter(item => {
        if (todoFilter.value === 2) {
            return !item.done;
        }
        if (todoFilter.value === 3) {
            return item.done;
        }
        return true;
    });
};

const logoutFile = () => {
    var blob = new Blob([todoListString.value], { type: '' });
    const name = dateFormat(new Date(), 'yyyyMMddhhmmss') + '.json';
    saveAs(blob, name);
};

const uploadFile = file => {
    console.log(file);
    if (file.raw.type !== 'application/json') {
        ctx.$message.error('仅支持json文件');
        return;
    }
    let reader = new FileReader();
    reader.readAsText(file.raw);
    reader.onload = e => {
        try {
            console.log(JSON.parse(e.target.result));
            todoList = todoList.concat(JSON.parse(e.target.result));
            updateTodo();
        } catch (e) {
            ctx.$message.error('json格式错误');
        }
    };
};

let codeVisible = ref(false);
let todoListString = ref(JSON.stringify(todoList));
const showCode = () => {
    codeVisible.value = true;
    todoListString.value = JSON.stringify(todoList);
    console.log(todoListString);
};

const updateCode = () => {
    try {
        todoList = JSON.parse(todoListString.value);
        updateTodo();
        codeVisible.value = false;
    } catch (e) {
        ctx.$message.error('json格式错误');
    }
};

const deleteTodo = (item,index)=>{
    console.log(item)
    todoList.forEach(todo=>{
        if(todo.date === item.date){
             todoList.splice(index,1)
        }
    })
    updateTodo();
}

const dateFormat = (date, fmt)=>{
    fmt = fmt || 'yyyy-MM-dd hh:mm:ss'
    const o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
    }
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    for (const k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
            const str = o[k] + ''
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : ('00' + str).substr(str.length))
        }
    }
    return fmt
}
</script>

<style scoped lang="less">
.todo-wrap {
    width: 40%;
    margin: 0 auto;
    .todo-top {
        display: flex;
        justify-content: space-around;
        align-items: center;
        margin: 20px 0;
        .todo-input {
            height: 50px;
            border-radius: 50px;
            padding: 20px;
        }
    }
    .todo-list {
        border: 1px solid rgb(235, 238, 245);
        padding: 30px;
        margin: 20px 0;
        .todo-detail {
            width: 100%;
            display: flex;
            flex-direction: column;
            margin-bottom: 20px;
            position: relative;
            .todo-detail-item {
                width: 100%;
                min-height: 40px;
                display: flex;
                align-items: center;
                justify-content: flex-start;
                span {
                    width: 100px;
                }
            }
            .todo-detail-item-btn {
                position: absolute;
                width: 100px;
                right: 0%;
                top: 35%;
                display: flex;
                justify-content: flex-end;
            }
        }
    }
}

:deep .el-collapse-item__header {
    padding: 0 30px;
    position: relative;
    color: #409eff;
}
:deep .el-collapse-item__header::before {
    content: '';
    width: 8px;
    height: 8px;
    left: 10px;
    border-radius: 50%;
    background-color: #409eff;
    position: absolute;
}
:deep .todo-finished .el-collapse-item__header {
    color: #b3b3b3 !important;
}
:deep .todo-finished .el-collapse-item__header::before {
    content: '';
    width: 8px;
    height: 8px;
    left: 10px;
    border-radius: 50%;
    background-color: #b3b3b3 !important;
    position: absolute;
}
:deep .el-collapse-item__content {
    padding: 0 10px;
}
</style>
